//
//  HistoryMessageController.m
//  SouthChina
//
//  Created by creator_lq on 15/1/7.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "HistoryMessageController.h"
#import "StorageEngine.h"
#import "ImageShowerController.h"

@interface HistoryMessageController (){
    
    NSMutableArray *msgList;
    PublicAccount *publicAccount;
    MessageSession *session;
    MessageAudioRecoder *recoder;

    NSMutableDictionary *heightForCell;

}

@end

@implementation HistoryMessageController

@synthesize publicId;

- (void)viewDidLoad {
    [super viewDidLoad];

    publicAccount = [PublicAccountDao queryForId:publicId];
    
    if (!publicId) {
        [self addTitleBarWithBackBtn:@"未知公众号" needReturn:YES];
        return;

    }
    heightForCell =  [[NSMutableDictionary alloc] initWithCapacity:10];
    session = [[MessageSession alloc]initWithData:@"sessionId" sesType:@"sessionType" oppositeId:DE.userId title:@"" text:@"" sessionPic:publicAccount.headImg isremind:@"1" updatime:[NSDate date] otherInfo:nil];

    [self addTitleBarWithBackBtn:publicAccount.appName needReturn:YES];
    _messageTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, self.view.frame.size.height-TITLE_BAR_HEGIHT-(YNEW)) style:UITableViewStylePlain];
    _messageTableview.tableHeaderView.backgroundColor = [UIColor whiteColor];

    _messageTableview.separatorStyle = NO;
    _messageTableview.delegate = self;
    _messageTableview.bounces= NO;
    _messageTableview.dataSource = self;
    _messageTableview.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:239/255.0f alpha:0.9];
    //防止iOS8下面的内存警告
    _messageTableview.rowHeight =44.0f;
    [self.view addSubview:_messageTableview];
    [self getHistoryMessageData];

}


-(void)getHistoryMessageData{
    
    
    [DE serverCall:@"queryAppHisMass" params:@{@"publicId":publicId} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        if (success) {
            
            msgList = [[NSMutableArray alloc] init];
            NSArray *tempList = [data objectForKey:@"msgs"];
             
            for (int i = 0; tempList && i<tempList.count; i++) {
                NSDictionary * map = [tempList objectAtIndex:i];
                NSDictionary * content = [[tempList objectAtIndex:i] objectForKey:@"content"];
                Message *msg= [[Message alloc]initWithData:content msgId:[map objectForKey:@"id"] updateTime:[[map objectForKey:@"update_time"] dateFromString]];
                
                [msgList addObject:msg];
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (msgList.count>0) {
                    [_messageTableview reloadData];
                }else{
                    //[self showAlerHUD:@"未获取到历史消息！"];
                    [self showAlerHUD:@"暂时没有历史消息！"];
                }
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showAlerHUD:@"获取历史消息失败！"];
            });

        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [msgList count];
}
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    Message *message = [msgList objectAtIndex:indexPath.row];
//    Message *preMessage =nil;
//    if (indexPath.row>0) {
//        preMessage =[msgList objectAtIndex:indexPath.row-1];
//    }
//    
//    if([message.mediaType isEqualToString:MEDIATYPE_TEXT] ||[message.mediaType isEqualToString:MEDIATYPE_AUDIO]
//       ||[message.mediaType isEqualToString:MEDIATYPE_PICTURE]){
//        if ([message isMine]) {
//            static NSString * CellIdentifier = @"MessageSendCell";
//            MessageSendCell* cell = (MessageSendCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
//            if (!cell) {
//                cell = [[MessageSendCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
//                
//                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//            }
//            
//            [cell setMsgCellValue:message preMessage:preMessage session:session];
//            return cell;
//            
//        }else{
//            static NSString * CellIdentifier = @"MessageReceiveCell";
//            MessageReceiveCell* cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
//            if (!cell) {
//                cell = [[MessageReceiveCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
//                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//            }
//            
//            [cell setMsgCellValue:message preMessage:preMessage session:session];
//            return cell;
//            
//        }
//    }
//    
//    else if([MEDIATYPE_NEWS isEqualToString:message.mediaType]){
//        
//        NSDictionary *allmap =[message getValue:@"news"];
//        if (allmap) {
//            NSArray * artlist = [allmap objectForKey:@"Articles"];
//            //多图文
//            if (artlist && [artlist count]>1) {
//                
//                static NSString * CellIdentifier = @"MultipleNewsCell";
//                MultipleNewsCell* cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
//                if (!cell) {
//                    cell = [[MultipleNewsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
//                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//                }
//                
//                [cell setMsgCellValue:message publicId:publicId];
//                return cell;
//                
//            }else{
//                
//                static NSString * CellIdentifier = @"SingleNewsCell";
//                SingleNewsCell* cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
//                if (!cell) {
//                    cell = [[SingleNewsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
//                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//                }
//                
//                [cell setMsgCellValue:message publicId:publicId];
//                return cell;
//                
//            }
//        }
//        
//    }
//    
//    else if([MEDIATYPE_URL isEqualToString:message.mediaType]){
//        static NSString * CellIdentifier = @"UrlCell";
//        UrlCell* cell = (UrlCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
//        if (!cell) {
//            cell = [[UrlCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
//            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//        }
//        [cell setMsgCellValue:message publicId:publicId];
//        
//        return cell;
//        
//    }
//    else if([MEDIATYPE_SIGN isEqualToString:message.mediaType]){
//        static NSString * CellIdentifier = @"SignCell";
//        SignCell* cell = (SignCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
//        if (!cell) {
//            cell = [[SignCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
//            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//        }
//        [cell setMsgCellValue:message publicId:publicId];
//        
//        return cell;
//    }
//    
//    return nil;
//    
//}
//


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    Message *message = [msgList objectAtIndex:indexPath.row];
    Message *preMessage =nil;
    if (indexPath.row>0) {
        preMessage =[msgList objectAtIndex:indexPath.row-1];
    }
    
    if([message.mediaType isEqualToString:MEDIATYPE_TEXT] ||[message.mediaType isEqualToString:MEDIATYPE_AUDIO]
       ||[message.mediaType isEqualToString:MEDIATYPE_PICTURE]){
        if ([message isMine]) {
            static NSString * CellIdentifier = @"MessageSendCell";
            MessageSendCell* cell = (MessageSendCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
            if (!cell) {
                cell = [[MessageSendCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            }
            
            [cell setMsgCellValue:message preMessage:preMessage session:session];
            return cell;
            
        }else{
            static NSString * CellIdentifier = @"MessageReceiveCell";
            MessageReceiveCell* cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
            if (!cell) {
                cell = [[MessageReceiveCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            }
            
            [cell setMsgCellValue:message preMessage:preMessage session:session];
            return cell;
            
        }
    }
    
    else if([MEDIATYPE_NEWS isEqualToString:message.mediaType]){
        
        NSDictionary *allmap =[message getValue:@"news"];
        if (allmap) {
            NSArray * artlist = [allmap objectForKey:@"Articles"];
            //多图文
            if (artlist && [artlist count]>1) {
                
                static NSString * CellIdentifier = @"MultipleNewsCell";
                MultipleNewsCell* cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
                if (!cell) {
                    cell = [[MultipleNewsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                }
                
                [cell setMsgCellValue:message publicId:session.oppositeId];
                return cell;
                
            }else{
                
                static NSString * CellIdentifier = @"SingleNewsCell";
                SingleNewsCell* cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
                if (!cell) {
                    cell = [[SingleNewsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                }
                
                [cell setMsgCellValue:message publicId:session.oppositeId];
                return cell;
                
            }
        }
        
    }
    
    else if([MEDIATYPE_URL isEqualToString:message.mediaType]){
        static NSString * CellIdentifier = @"UrlCell";
        UrlCell* cell = (UrlCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[UrlCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        [cell setMsgCellValue:message publicId:session.oppositeId];
        
        return cell;
        
    }
    else if([MEDIATYPE_SIGN isEqualToString:message.mediaType]){
        static NSString * CellIdentifier = @"SignCell";
        SignCell* cell = (SignCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[SignCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        [cell setMsgCellValue:message publicId:session.oppositeId];
        return cell;
    }
    
    return nil;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return [self cellForEachHeight:indexPath.row];
    
}

#pragma mark - Table view Helper
- (CGFloat)cellForEachHeight:(NSInteger)index
{
    
    Message *message = [msgList objectAtIndex:index];
    Message *preMessage =nil;
    
    CGFloat height = [[heightForCell objectForKey:message.mID] floatValue];
    if (height != 0){
        return height;
    }
    
    CGFloat curHeight = 0;
    
    if (index>0) {
        preMessage =[msgList objectAtIndex:index-1];
    }
    BOOL isShwoTimeLable = NO;
    if (preMessage) {
        NSTimeInterval secondsBetweenDates= [message.upate_time timeIntervalSinceDate:preMessage.upate_time];
        isShwoTimeLable = secondsBetweenDates>=30.0f;
    }else{
        isShwoTimeLable =YES;
    }
    
    if([message.mediaType isEqualToString:MEDIATYPE_TEXT] ||[message.mediaType isEqualToString:MEDIATYPE_AUDIO]
       ||[message.mediaType isEqualToString:MEDIATYPE_PICTURE]){
        NSString *contentText = @"";
        if ([MEDIATYPE_PICTURE isEqualToString:message.mediaType]) {
            return PICTURE_CELL_HEIGTH +  (isShwoTimeLable? TIME_LABEL_HEGIHT+CELL_COM_GAP*3:CELL_COM_GAP*2);
        }
        else if([MEDIATYPE_AUDIO isEqualToString:message.mediaType]){
            contentText = @"X秒";
        }else if([MEDIATYPE_TEXT isEqualToString:message.mediaType]){
            contentText = message.text;
        }
        CGFloat height = 0;
        M80AttributedLabel *label = [[M80AttributedLabel alloc]initWithFrame:CGRectZero];
        [BaseTableCell addCoreTextMessage:contentText label:label];
        CGSize size = [label sizeThatFits:CGSizeMake(MAX_CONTENT_WIDTH, CGFLOAT_MAX)];
        height = size.height;
        curHeight = height +  (isShwoTimeLable? (TIME_LABEL_HEGIHT)+CELL_COM_GAP*3:CELL_COM_GAP*2) +TEXT_BUBBLE_GAP*2;
    }
    
    else if([MEDIATYPE_NEWS isEqualToString:message.mediaType]){
        NSDictionary *allmap =[message getValue:@"news"];
        if (allmap) {
            NSArray * artlist = [allmap objectForKey:@"Articles"];
            //多图文
            if (artlist && [artlist count]>1) {
                curHeight= BIG_IMAGE_HEIGHT +2*NEW_CELL_COM_GAP +(artlist.count-1) *CELL_OTHER_CELL;
            }else{
                curHeight= SINGLE_NEWS_CELL;
            }
        }
    }
    else if([MEDIATYPE_URL isEqualToString:message.mediaType]){
        NSDictionary * dataMap =[message getValue:@"url"];
        CGSize contentSize = [[dataMap objectForKey:@"title"] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(SCREEN_WIDTH-4*NEW_CELL_COM_GAP, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping];
        curHeight= contentSize.height +6*NEW_CELL_COM_GAP +TIME_AUTHOR_LOOK_HEIGHT*2;
        
    } else if([MEDIATYPE_SIGN isEqualToString:message.mediaType]){
        CGSize contentSize = [message.text sizeWithFont:[UIFont systemFontOfSize:FONT_TITLE_SIZE_SIGN] constrainedToSize:CGSizeMake(SCREEN_WIDTH-5*NEW_CELL_COM_GAP-SIGN_BTN_WIDTH, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping];
        curHeight = TIME_SING_HEIGHT +(6*NEW_CELL_COM_GAP) + contentSize.height;
        
    }else{
        curHeight =  SINGLE_NEWS_CELL;
    }
    [heightForCell setObject:@(curHeight) forKey:message.mID];
    
    return curHeight;
}


//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    Message *message = [msgList objectAtIndex:indexPath.row];
//    Message *preMessage =nil;
//    if (indexPath.row>0) {
//        preMessage =[msgList objectAtIndex:indexPath.row-1];
//    }
//    BOOL isShwoTimeLable = NO;
//    if (preMessage) {
//        NSTimeInterval secondsBetweenDates= [message.upate_time timeIntervalSinceDate:preMessage.upate_time];
//        isShwoTimeLable = secondsBetweenDates>=30.0f;
//    }else{
//        isShwoTimeLable =YES;
//    }
//    
//    if([message.mediaType isEqualToString:MEDIATYPE_TEXT] ||[message.mediaType isEqualToString:MEDIATYPE_AUDIO]
//       ||[message.mediaType isEqualToString:MEDIATYPE_PICTURE]){
//        
//        NSString *contentText = @"";
//        
//        if ([MEDIATYPE_PICTURE isEqualToString:message.mediaType]) {
//            
//            return PICTURE_CELL_HEIGTH +  (isShwoTimeLable? TIME_LABEL_HEGIHT+CELL_COM_GAP*3:CELL_COM_GAP*2);
//            
//        }
//        
//        else if([MEDIATYPE_AUDIO isEqualToString:message.mediaType]){
//            contentText = @"X秒";
//        }else if([MEDIATYPE_TEXT isEqualToString:message.mediaType]){
//            contentText = message.text;
//        }
//        
//        CGSize contentSize = [contentText sizeWithFont:[UIFont systemFontOfSize:TEXT_CONTENT_FONT] constrainedToSize:CGSizeMake(MAX_CONTENT_WIDTH, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping];
//        
//        int msgConentHeight =contentSize.height + TEXT_BUBBLE_GAP_RGIHT*2;
//        return msgConentHeight +  (isShwoTimeLable? TIME_LABEL_HEGIHT+CELL_COM_GAP*3:CELL_COM_GAP*2);
//        
//        
//    }
//    else if([MEDIATYPE_NEWS isEqualToString:message.mediaType]){
//        
//        NSDictionary *allmap =[message getValue:@"news"];
//        if (allmap) {
//            NSArray * artlist = [allmap objectForKey:@"Articles"];
//            //多图文
//            if (artlist && [artlist count]>1) {
//                
//                return BIG_IMAGE_HEIGHT +2*NEW_CELL_COM_GAP +(artlist.count-1) *CELL_OTHER_CELL;
//                
//            }else{
//                return SINGLE_NEWS_CELL;
//            }
//        }
//    }
//    else if([MEDIATYPE_URL isEqualToString:message.mediaType]){
//        NSDictionary * dataMap =[message getValue:@"url"];
//        CGSize contentSize = [[dataMap objectForKey:@"title"] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(SCREEN_WIDTH-4*NEW_CELL_COM_GAP, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping];
//        
//        return contentSize.height +6*NEW_CELL_COM_GAP +TIME_AUTHOR_LOOK_HEIGHT*2;
//        
//    } else if([MEDIATYPE_SIGN isEqualToString:message.mediaType]){
//        
//        CGSize contentSize = [message.text sizeWithFont:[UIFont systemFontOfSize:FONT_TITLE_SIZE_SIGN] constrainedToSize:CGSizeMake(SCREEN_WIDTH-5*NEW_CELL_COM_GAP-SIGN_BTN_WIDTH, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping];
//        
//        return TIME_SING_HEIGHT +(6*NEW_CELL_COM_GAP) + contentSize.height;;
//    }
//    
//    return SINGLE_NEWS_CELL;
//    
//}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Message *msg = [msgList objectAtIndex:indexPath.row];
    if ([MEDIATYPE_AUDIO isEqualToString:msg.mediaType]) {
        
        NSString *loaclPath = [msg getValue:@"file"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //如果存在本地文件
        if([fileManager fileExistsAtPath:loaclPath]) {
            NSURL *url = [NSURL fileURLWithPath:loaclPath];
            if (!recoder) {
                recoder = [[MessageAudioRecoder alloc] init];
            }
            [recoder playRecordSoundWithURL:url];
        }
        else {
            
            NSString *textUrl = [NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,msg.text];
            NSString *textPath =[StorageEngine readloadNetFile:textUrl];
            //如果下载过
            if([fileManager fileExistsAtPath:textPath]) {
                NSURL *url = [NSURL fileURLWithPath:textPath];
                if (!recoder) {
                    recoder = [[MessageAudioRecoder alloc] init];
                }
                [recoder playRecordSoundWithURL:url];
            }else{
                //如果下载成功
                if([StorageEngine downloadNetFile:textUrl]){
                    NSURL *url = [NSURL fileURLWithPath:textPath];
                    if (!recoder) {
                        recoder = [[MessageAudioRecoder alloc] init];
                    }
                    [recoder playRecordSoundWithURL:url];
                }
                
            }
            
        }
        
    }
    //单新闻/签到跳转
    else if([MEDIATYPE_NEWS isEqualToString:msg.mediaType] ||[MEDIATYPE_URL isEqualToString:msg.mediaType]){
        WebViewController * detail = [[WebViewController alloc] init];
        
        if([MEDIATYPE_URL isEqualToString:msg.mediaType]){
            NSDictionary * dataMap =[msg getValue:@"url"];
            NSString *urlStr =[dataMap objectForKey:@"url" ];
            detail.webUrl = [urlStr hasPrefix:@"http"]?urlStr:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,urlStr];
            
        }else{
            NSDictionary * allmap =[msg getValue:@"news"];
            NSArray * artlist = [allmap objectForKey:@"Articles"];
            NSDictionary *clickData = [artlist objectAtIndex:0];
            detail.webUrl = [clickData objectForKey:@"Url" ];
        }
        detail.publicId = session.oppositeId;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:detail animated:NO];
    }
    
    else if([MEDIATYPE_PICTURE isEqualToString:msg.mediaType]){
        
        ImageShowerController * imgCont = [[ImageShowerController alloc]init];
        if ([msg isMine]) {
            if ([msg getValue:@"file"]) {
                imgCont.filePath =[msg getValue:@"file"];
            }else{
                imgCont.filePath =[msg.text hasPrefix:@"http"]?msg.text:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,msg.text];
            }
        }else{
            NSString *url =[msg getValue:@"url"];
            imgCont.filePath = [url hasPrefix:@"http"]?url:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,url];
        }
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:imgCont animated:NO];
        
        
    }

}

@end
